package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.cache.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.repository.UserMongoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserMongoRepository repository;

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public void save(UserInfo userInfo) {
        userInfo.setId(null);
        repository.save(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        repository.save(userInfo);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public UserInfo get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<UserInfo> list() {
        return repository.findAll();
    }

    @Override
    public boolean checkPhone(String phone) {
        UserInfo userInfo = repository.findByPhone(phone);
        return userInfo != null;

    }

    @Override
    public void sendVerifyCode(String phone ,String smsUrl ,String appkey) {
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
        StringBuilder sb = new StringBuilder();
        sb.append("您生成的验证码是：").
                append(code).append("请在").append(Consts.VERIFY_CODE_VAI_TIME).append("分钟内使用。");
        // 发送短信
        System.out.println(sb.toString());
//        RestTemplate restTemplate = new RestTemplate();
//        // 第一个参数是请求url 第二个是返回类型 , 第三个是手机号,第四个是占位符第2位,代表发送的语句,第五个是appkey
//        String ret = restTemplate.getForObject(smsUrl, String.class, phone, "【创信】" + sb.toString(), appkey);
//        if(!ret.contains("Success")){
//            throw new LogicException("短信发送失败");
//        }
//        System.out.println(ret);

        userInfoRedisService.setVerifyCode(phone , code);
    }

    @Override
    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        // 1.判断用户输入的参数是否为空
        AssertUtil.hasLength(phone , "手机号不能为空");
        AssertUtil.hasLength(nickname , "昵称不能为空");
        AssertUtil.hasLength(password , "密码不能为空");
        AssertUtil.hasLength(rpassword , "确认密码不能为空");
        AssertUtil.hasLength(verifyCode , "验证码不能为空");

        // 2.两次密码是否一致
        AssertUtil.isEquals(password , rpassword , "两次密码输入不一致");
        // 3.判断手机号是否唯一
        if(checkPhone(phone)){
            throw new LogicException("该手机号已经注册过");
        }
        // 4.判断手机号格式是否符合
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
        if (!Pattern.matches(regex, phone)) {
            throw new LogicException("手机号码格式不正确");
        }
        // 5.判断验证码是否正确
        String code = userInfoRedisService.getVerifyCode(phone);
        if( code == null){
            throw new LogicException("验证码已失效");
        }else if (!code.equalsIgnoreCase(verifyCode)){
            throw new LogicException("验证码错误");
        }


        // 6.注册
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setPhone(phone);
        userInfo.setEmail("");
        userInfo.setPassword(password);
        userInfo.setGender(userInfo.GENDER_SECRET);
        userInfo.setLevel(1);
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfo.setInfo("这个人很懒,什么都没有留下");
        userInfo.setState(userInfo.STATE_NORMAL);

        //throw new RuntimeException("111111111111");

        repository.save(userInfo);
    }

    @Override
    public UserInfo login(String username, String password) {
        // 通过手机号查询数据库中是否有该账户(手机号就是账户) , 获取密码的时候要加密
        UserInfo userInfo = repository.findByPhone(username);
        if(userInfo == null || !password.equals(userInfo.getPassword())){
            throw new LogicException("该手机号已注册");
        }
        return userInfo;
    }


}
